﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Diagnostics;
using MediaBrowser.Library.Persistance;
using MediaBrowser.Library.Entities;
using MediaBrowser.Library.Providers.Attributes;
using MediaBrowser.Library.Providers;
using MediaBrowser.Library.Logging;

namespace theHTPCPeopleProvider
{
    [RequiresInternet]
    [SupportedType(typeof(Person))]
    public class theHTPCPeopleProvider : BaseMetadataProvider
    {
        [Persist]
        DateTime lastFetched = DateTime.MinValue;

        public override void Fetch()
        {

            {
                lastFetched = DateTime.Now;
                string imageurl = CreateUrl(Item.Name);
                string doc = Fetch(imageurl);
                if (doc != null) Item.PrimaryImagePath = imageurl;
                if (doc == null) return;
              
            }
        }
        //thanks soultaker :)
        private static string CreateUrl(string actorName)
        {
            if (Regex.IsMatch(actorName, "[ÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ]"))
                return string.Format("http://ibn.thehtpc.net/{0}/folder.jpg", HttpUtility.UrlEncode(actorName, Encoding.GetEncoding("iso-8859-1")));
            else
                return string.Format("http://ibn.thehtpc.net/{0}/folder.jpg", HttpUtility.HtmlEncode(actorName));
        }

        public override bool NeedsRefresh()
        {
            // only fetch missing images 
            return Item.PrimaryImagePath == null && (DateTime.Now - lastFetched).Days > 30;
        }

        private static object fetchLock = new object();
        private string Fetch(string url)
        {
            Logger.ReportInfo("theHTPCPeopleProvide is requesting: " + url);

            int attempt = 0;
            while (attempt < 2)
            {
                attempt++;
                try
                {
                    lock (fetchLock) // don't require as much reduce rate as in nndb plugin
                    {
                        WebRequest req = HttpWebRequest.Create(url);
                        req.Timeout = 30000;
                        WebResponse resp = req.GetResponse();
                        try
                        {
                            using (Stream s = resp.GetResponseStream())
                            {
                                StreamReader sr = new StreamReader(s);
                                return sr.ReadToEnd();
                            }
                        }
                        finally
                        {
                            resp.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ReportWarning("Unable to fetch: " + url, ex);
                }
            }
            return null;
        }
    }
}

